import React, { Suspense } from "react";
import { useQuery } from "react-query";

function Img ({ src, alt, ...props }: {src: string; alt: string}) {
  const { data: imgObject } = useQuery<HTMLImageElement>(
    src,
    () => new Promise((resolve) => {
      const img = new Image();
      img.onload = () => resolve(img);
      img.src = src;
    }),
    {suspense: true}
  );
  return <img src={imgObject?.src} alt={alt} {...props} style={{borderRadius: '50%'}}/>
}

export default function Avatar ({src, alt, fallbackSrc, ...props}: {src: string; alt: string; fallbackSrc: string}) {
  return (
    <div className="user-avatar" style={{width: '60px', height: '60px'}}>
      <Suspense
        fallback={<img src={fallbackSrc} alt="Fallback Avatar"/>}
      >
        <Img src={src} alt={alt} {...props}/>
      </Suspense>
    </div>
  );
}